/*
 * @Date: 2023-09-07 14:56:32
 * @LastEditTime: 2023-09-08 12:06:44
 * 介绍:
 */
/**
 * base64转file对象
 * @param dataurl base64字符串
 * @param filename 文件名
 * @param type 类型 'image/jpeg'
 * @returns
 */
export function dataUrlToFile(
  dataurl: string,
  filename: string,
  type: string = "image/jpeg"
) {
  // 获取到base64编码
  const arr = dataurl.split(",");
  // 将base64编码转为字符串
  const bstr = window.atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n); // 创建初始化为0的，包含length个元素的无符号整型数组
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, {
    type,
  });
}

/**
 * base64转blob对象
 * @param base64UrlStr
 * @param type 类型 'image/jpeg'
 * @returns
 */
export function dataUrlToBlob(
  base64UrlStr: string,
  type: string = "image/jpeg"
) {
  return new Blob([base64UrlStr], { type });
}
/**
 *
 * @param blob
 * @param name
 * @param type 类型 'image/jpeg'
 * @returns
 */
export function blobToFile(
  blob: Blob,
  name: string,
  type: string = "image/jpeg"
) {
  return new File([blob], name, { type });
}
/**
 * 压缩图片到指定大小
 * @param imgFile 图片文件
 * @param size 最大大小
 * @param maxCount 最大输了
 * @returns 
 */
export async function imageCompress(
  imgFile: File,
  size: number,
  maxCount = 10
) {
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d")!;
  const image = new Image();
  let ratio = 0.9;
  for (let i = 1; i < maxCount; i++) {
    console.log(`第${i}次压缩`);
    image.src = URL.createObjectURL(imgFile);
    imgFile = await new Promise<File>((resolve, reject) => {
      image.onload = () => {
        URL.revokeObjectURL(image.src);
        const w = image.width;
        const h = image.height;
        canvas.width = w;
        canvas.height = h;
        ctx.drawImage(image, 0, 0, w, h);
        const dataUrl = canvas.toDataURL(imgFile.type, ratio);
        imgFile = dataUrlToFile(dataUrl, imgFile.name);
        ratio -= 0.1;
        resolve(imgFile);
      };
    });
    if (imgFile.size <= size) return imgFile;
  }
  return imgFile;
}
